/**
 * 
 */
package com.mzba.place.ui;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.mapapi.search.MKAddrInfo;
import com.baidu.mapapi.search.MKBusLineResult;
import com.baidu.mapapi.search.MKDrivingRouteResult;
import com.baidu.mapapi.search.MKPoiResult;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.mapapi.search.MKSearchListener;
import com.baidu.mapapi.search.MKSuggestionResult;
import com.baidu.mapapi.search.MKTransitRouteResult;
import com.baidu.mapapi.search.MKWalkingRouteResult;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.mzba.place.BasicActivity;
import com.mzba.place.PlaceApplication;
import com.mzba.place.R;
import com.mzba.place.utils.AppContext;

/**
 * @author iris
 *
 */
public class MapMyLocalActivity extends BasicActivity implements Callback {
	
	public MapView mMapView = null;
	private MapController mMapController = null;
	public PlaceApplication app;
	public LocationClient mLocClient;
	public MKSearch mSearch = null;
	
	private Handler handler;
	private int latitude;
	private int longitude;
	private String address;
	private Drawable mypositionDrawable;
	private int mLastMotionX, mLastMotionY;
	private boolean isMoved;
	// 移动的阈值
	private static final int TOUCH_SLOP = 20;
	
	private final int menu_confirm = 1;

	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setSupportProgressBarIndeterminateVisibility(false);
		setContentView(R.layout.choose_location);
		actionBar.show();
		actionBar.setDisplayShowTitleEnabled(true);
		setTitle("长按地图选择位置");
		
		handler = new Handler(this);
		app = (PlaceApplication) getApplication();
        if (app.mBMapManager == null) {
            app.mBMapManager = new BMapManager(this);
            app.mBMapManager.init(PlaceApplication.strKey, new PlaceApplication.MyGeneralListener());
        }
        app.getMyListener().setHander(handler);
        mLocClient = app.mLocationClient;
        
        mMapView = (MapView) findViewById(R.id.bmapView);
        mMapController = mMapView.getController();
        mMapController.enableClick(true);
        mMapController.setZoom(18);
        mMapView.setDoubleClickZooming(true);
        mMapView.setOnTouchListener(mapTouchListener);
        mSearch = new MKSearch();
        initMKSearch();
        
        mypositionDrawable = getResources().getDrawable(R.drawable.ic_map_current_position);
        loading();
		new Thread() {
			public void run() {
				setLocationOption();
				if (mLocClient != null && mLocClient.isStarted()) {
					mLocClient.requestLocation();
				} else {
					mLocClient.start();
					mLocClient.requestLocation();
				}
			};
		}.start();
	}
	
	/**长按*/
	private Runnable mLongPressRunnable = new Runnable() {
		@Override
		public void run() {
			final GeoPoint pt = mMapView.getProjection().fromPixels((int) mLastMotionX, (int) mLastMotionY);
			mSearch.reverseGeocode(pt);
		}
	};
	
	/** 长按地图添加坐标点 */
	private View.OnTouchListener mapTouchListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			int x = (int) event.getX();
			int y = (int) event.getY();
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				mLastMotionX = x;
				mLastMotionY = y;
				isMoved = false;
				mMapView.postDelayed(mLongPressRunnable, 1000);
				break;
			case MotionEvent.ACTION_MOVE:
				if (isMoved)
					break;
				if (Math.abs(mLastMotionX - x) > TOUCH_SLOP || Math.abs(mLastMotionY - y) > TOUCH_SLOP) {
					// 移动超过阈值，则表示移动了
					isMoved = true;
					mMapView.removeCallbacks(mLongPressRunnable);
				}
				break;
			case MotionEvent.ACTION_UP:
				// 释放了
				mMapView.removeCallbacks(mLongPressRunnable);
				break;
			}
			return false;
		}
	};
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, menu_confirm, 0, "确定").setIcon(R.drawable.abs__ic_cab_done_holo_dark).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;
		case menu_confirm:
			Intent intent = new Intent(this, ReportUploadActivity.class);
			intent.putExtra("latitude", latitude);
			intent.putExtra("longitude", longitude);
			intent.putExtra("address", address);
			setResult(RESULT_OK, intent);
			finish();
			break;
		default:
			break;
		}
		return false;
	}
	
	private void setLocationOption() {
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);			
		option.setCoorType("bd09ll");			
		option.setAddrType("all");	
		option.setScanSpan(0);
		option.setPriority(LocationClientOption.GpsFirst);      
		option.setPoiNumber(10);
		option.disableCache(true);		
		mLocClient.setLocOption(option);
	}
	
	private void initMKSearch() {
		mSearch.init(app.mBMapManager, new MKSearchListener() {
			
			@Override
			public void onGetWalkingRouteResult(MKWalkingRouteResult res, int error) { }
			
			@Override
			public void onGetTransitRouteResult(MKTransitRouteResult res, int error) { }
			
			@Override
			public void onGetSuggestionResult(MKSuggestionResult res, int error) { }
			
			@Override
			public void onGetPoiResult(MKPoiResult arg0, int res, int error) { }
			
			@Override
			public void onGetPoiDetailSearchResult(int res, int error) { }
			
			@Override
			public void onGetDrivingRouteResult(MKDrivingRouteResult res, int error) { }
			
			@Override
			public void onGetBusDetailResult(MKBusLineResult res, int error) { }
			
			@Override
			public void onGetAddrResult(MKAddrInfo res, int error) { 
				destroyDialog();
				try {
					if (error != 0) {
						return;
					}
					if (res.geoPt != null) {
						latitude = res.geoPt.getLatitudeE6();
						longitude = res.geoPt.getLongitudeE6();
						address = res.strAddr;
						
						OverlayItem item = new OverlayItem(res.geoPt, null, null);
						ItemizedOverlay<OverlayItem> overlay = new ItemizedOverlay<OverlayItem>(mypositionDrawable, mMapView);
						overlay.removeAll();
						overlay.addItem(item);
						mMapView.getOverlays().clear();
						mMapView.getOverlays().add(overlay);
						mMapView.refresh();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
		});
	}

	@Override
	public boolean handleMessage(Message msg) {
		try {
			switch (msg.what) {
			case AppContext.LOCATE:
				destroyDialog();
				latitude = (int) (app.latitude * 1E6);
				longitude = (int) (app.longitude * 1E6);
				if (latitude != 0 && longitude != 0) {
					GeoPoint pt = new GeoPoint(latitude, longitude);
					mSearch.reverseGeocode(pt);
					mMapController.animateTo(pt);
					OverlayItem item = new OverlayItem(pt, null, null);
					ItemizedOverlay<OverlayItem> overlay = new ItemizedOverlay<OverlayItem>(mypositionDrawable, mMapView);
					overlay.removeAll();
					overlay.addItem(item);
					mMapView.getOverlays().clear();
					mMapView.getOverlays().add(overlay);
					mMapView.refresh();
					loading();
					mSearch.reverseGeocode(pt);
				}
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	@Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }
    
    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
    }
    
    @Override
    protected void onDestroy() {
        mMapView.destroy();
        super.onDestroy();
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
    	super.onSaveInstanceState(outState);
    	mMapView.onSaveInstanceState(outState);
    	
    }
    
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
    	super.onRestoreInstanceState(savedInstanceState);
    	mMapView.onRestoreInstanceState(savedInstanceState);
    }
}
